#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
NSA5312 上位机软件启动脚本
NSA5312 Upper Computer Software Launcher

使用方法:
python run_nsa5312_app.py

或者直接双击运行此文件（如果已安装Python）
"""

import sys
import os
import traceback
from pathlib import Path

def check_dependencies():
    """检查依赖包"""
    missing_packages = []
    
    try:
        import PyQt5
    except ImportError:
        missing_packages.append("PyQt5")
    
    try:
        import serial
    except ImportError:
        missing_packages.append("pyserial")
    
    try:
        import numpy
    except ImportError:
        missing_packages.append("numpy")
    
    if missing_packages:
        print("错误：缺少以下依赖包：")
        for package in missing_packages:
            print(f"  - {package}")
        print("\n请运行以下命令安装依赖包：")
        print("pip install -r requirements.txt")
        return False
    
    return True

def setup_environment():
    """设置环境"""
    # 添加当前目录到Python路径
    current_dir = Path(__file__).parent
    if str(current_dir) not in sys.path:
        sys.path.insert(0, str(current_dir))
    
    # 设置工作目录
    os.chdir(current_dir)
    
    # 创建必要的目录
    directories = ['logs', 'exports', 'config']
    for directory in directories:
        (current_dir / directory).mkdir(exist_ok=True)

def main():
    """主函数"""
    print("NSA5312 上位机软件启动中...")
    print("=" * 50)
    
    # 检查依赖
    if not check_dependencies():
        input("按任意键退出...")
        return 1
    
    # 设置环境
    setup_environment()
    
    try:
        # 导入主窗口
        from main_window import main
        
        print("依赖检查完成，启动GUI界面...")
        
        # 启动应用程序
        return main()
        
    except ImportError as e:
        print(f"导入错误: {e}")
        print("请确保所有Python文件都在正确的位置")
        traceback.print_exc()
        input("按任意键退出...")
        return 1
        
    except Exception as e:
        print(f"启动失败: {e}")
        traceback.print_exc()
        input("按任意键退出...")
        return 1

if __name__ == "__main__":
    try:
        exit_code = main()
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n用户中断程序")
        sys.exit(0)
    except Exception as e:
        print(f"程序异常退出: {e}")
        traceback.print_exc()
        input("按任意键退出...")
        sys.exit(1)